<?php

namespace app\common\controller;

use Exception;

class UserSigService
{
    private $sdkAppId; // SDKAppID
    private $secretKey; // 密钥

    public function __construct($sdkAppId, $secretKey)
    {
        $this->sdkAppId = $sdkAppId;
        $this->secretKey = $secretKey;
    }

    /**
     * 生成 UserSig
     *
     * @param string $userId 用户 ID
     * @param int $expire 有效期（秒）
     * @return string
     * @throws Exception
     */
    public function generateUserSig($userId, $expire = 3600)
    {
        $currentTime = time();
        $data = [
            'TLS.ver' => '2.0',
            'TLS.identifier' => $userId,
            'TLS.sdkappid' => $this->sdkAppId,
            'TLS.expire' => $expire,
            'TLS.time' => $currentTime,
        ];

        $base64UrlEncodedData = $this->base64UrlEncode(json_encode($data));
        $signature = hash_hmac('sha256', $base64UrlEncodedData, $this->secretKey, true);
        $base64UrlEncodedSignature = $this->base64UrlEncode($signature);

        $data['TLS.sig'] = $base64UrlEncodedSignature;
        return $this->base64UrlEncode(json_encode($data));
    }

    /**
     * Base64 URL 编码
     *
     * @param string $data
     * @return string
     */
    private function base64UrlEncode($data)
    {
        return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($data));
    }
}
